<template>
  <div class="detail">
    <el-form
      ref="postForm"
      :model="postForm"
      :rules="rules"
      label-position="right"
      label-width="130px"
    >
      <div class="form-data">
        <el-form-item label="父级菜单" prop="pid">
          <el-select
            v-model.number="postForm.pid"
            placeholder="父级菜单"
            style="width: 100%"
            @change="changePid"
          >
            <el-option :value="0" label="顶级菜单" />
            <tn-select-group
              :item="menuOptions"
              label-key="label"
              value-key="id"
              :parent-click="true"
            />
            <!-- <el-option v-for="item in menuOptions" :key="item.id" :value="item.id" :label="item.name + '(' + item.title + ')'" /> -->
          </el-select>
        </el-form-item>
        <el-form-item label="路由名称" prop="name">
          <el-input
            v-model="postForm.name"
            placeholder="路由名称"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="菜单名称" prop="title">
          <el-input
            v-model="postForm.title"
            placeholder="菜单名称"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="菜单图标" prop="icon">
          <icon-select v-model="postForm.icon" />
        </el-form-item>
        <el-form-item label="路由地址" prop="path">
          <el-input
            v-model="postForm.path"
            placeholder="路由地址"
            style="width: 100%"
          />
          <span v-show="postForm.is_link === 1" class="form-item-tips">请输入需要跳转链接的地址，以/结尾</span>
        </el-form-item>
        <el-form-item label="文件所在位置" prop="url">
          <el-input
            v-model="postForm.url"
            placeholder="文件所在位置"
            style="width: 100%"
          />
          <span class="form-item-tips">请输入路由所渲染文件所在的位置</span>
        </el-form-item>
        <el-form-item label="重定向地址" prop="redirect">
          <el-input
            v-model="postForm.redirect"
            placeholder="重定向地址"
            style="width: 100%"
            :disabled="postForm.is_click_in_breadcrumb === 0 ? true : false"
          />
          <span class="form-item-tips">请输入重定向的路由地址</span>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number
            v-model.number="postForm.sort"
            controls-position="right"
          />
        </el-form-item>
        <el-form-item label="隐藏" prop="hidden">
          <el-switch
            v-model.number="postForm.hidden"
            :active-value="1"
            :inactive-value="0"
          />
          <span class="form-item-tips">当前菜单是否不显示在侧边栏中</span>
        </el-form-item>
        <el-form-item label="链接" prop="is_link">
          <el-switch
            v-model.number="postForm.is_link"
            :active-value="1"
            :inactive-value="0"
          />
          <span class="form-item-tips">当前菜单是否为链接</span>
        </el-form-item>
        <el-form-item label="面包屑中点击" prop="is_click_in_breadcrumb">
          <el-switch
            v-model.number="postForm.is_click_in_breadcrumb"
            :active-value="1"
            :inactive-value="0"
          />
          <span class="form-item-tips">当前菜单是否可以在面包屑中点击</span>
        </el-form-item>
        <el-form-item label="面包屑中显示" prop="breadcrumb_show">
          <el-switch
            v-model.number="postForm.breadcrumb_show"
            :active-value="1"
            :inactive-value="0"
          />
          <span class="form-item-tips">当前菜单是否显示在面包屑中</span>
        </el-form-item>
        <el-form-item label="侧边栏总是显示" prop="always_show">
          <el-switch
            v-model.number="postForm.always_show"
            :active-value="1"
            :inactive-value="0"
          />
          <span class="form-item-tips">当前菜单是否总是显示在侧边栏中</span>
        </el-form-item>
        <el-form-item label="不缓存" prop="no_cache">
          <el-switch
            v-model.number="postForm.no_cache"
            :active-value="1"
            :inactive-value="0"
          />
          <span class="form-item-tips">当前菜单是否不使用缓存</span>
        </el-form-item>
        <el-form-item label="公用菜单" prop="public_menu">
          <el-switch
            v-model.number="postForm.public_menu"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch
            v-model.number="postForm.status"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
      </div>

      <sticky :class-name="'sub-navbar'">
        <el-button
          v-loading="loading"
          type="success"
          style="margin-left: 10px"
          @click="submitForm"
        >
          {{ isEdit ? '编辑' : '添加' }}
        </el-button>
      </sticky>
    </el-form>
  </div>
</template>

<script>
import Sticky from '@/components/Sticky'
import TnIconSelect from '@/components/TNIconSelect'
import TnSelectGroup from '@/components/TNSelectGroup'
import { getAllMenuNode, getChildrenCount, getAuthMenuByID, addAuthMenu, editAuthMenu } from '@/api/auth-menu'

const fields = {
  name: '路由名称',
  title: '菜单名称',
  path: '路由地址'
}

const validateRequire = (rule, value, callback) => {
  if (!value || value === '' || value.trim() === '') {
    const errMsg = fields[rule.field] + '为必填项'
    callback(new Error(errMsg))
  } else {
    callback()
  }
}

const validateHttpUrl = (rule, value, callback) => {
  if (!(/^(ht|f)tps?:\/\/[\w-]+(\.[\w-]+)+(:\d{1,5})?\/$/.test(value))) {
    const errMsg = '链接地址格式不正确'
    // this.showMessage(errMsg, 'error')
    callback(new Error(errMsg))
  } else {
    callback()
  }
}

export default {
  name: 'AuthMenuDetail',
  components: { Sticky, 'icon-select': TnIconSelect, TnSelectGroup },
  props: {
    id: {
      type: Number,
      default: 0
    },
    pid: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      isEdit: false,
      loading: false,
      tempRedirect: '',
      menuOptions: [],
      postForm: {
        pid: 0,
        name: '',
        title: '',
        icon: '',
        path: '',
        url: '',
        redirect: '',
        sort: 1,
        hidden: 0,
        is_link: 0,
        is_click_in_breadcrumb: 1,
        breadcrumb_show: 1,
        always_show: 0,
        no_cache: 0,
        public_menu: 0,
        status: 1
      },
      rules: {
        pid: [
          { required: true, message: '父级菜单不能为空' },
          { type: 'number', message: '父级菜单值格式不正确' }
        ],
        name: [
          { required: true, message: '路由名称不能为空' },
          { validator: validateRequire, trigger: 'blur' }
        ],
        title: [
          { required: true, message: '菜单名称不能为空' },
          { validator: validateRequire, trigger: 'blur' }
        ],
        path: [
          { required: true, message: '路由地址不能为空' },
          { validator: validateRequire, trigger: 'blur' }
        ],
        sort: [
          { required: true, message: '排序不能为空' },
          { type: 'number', message: '排序值格式不正确' }
        ],
        hidden: [
          { required: true, message: '隐藏不能为空' },
          { type: 'number', message: '隐藏值格式不正确' }
        ],
        is_link: [
          { required: true, message: '链接不能为空' },
          { type: 'number', message: '链接值格式不正确' }
        ],
        is_click_in_breadcrumb: [
          { required: true, message: '面包屑中点击不能为空' },
          { type: 'number', message: '面包屑中点击值格式不正确' }
        ],
        breadcrumb_show: [
          { required: true, message: '面包屑中显示不能为空' },
          { type: 'number', message: '面包屑中显示值格式不正确' }
        ],
        always_show: [
          { required: true, message: '侧边栏总是显示不能为空' },
          { type: 'number', message: '侧边栏总是显示值格式不正确' }
        ],
        no_cache: [
          { required: true, message: '不缓存不能为空' },
          { type: 'number', message: '不缓存值格式不正确' }
        ],
        public_menu: [
          { required: true, message: '公用菜单不能为空' },
          { type: 'number', message: '公用菜单值格式不正确' }
        ],
        status: [
          { required: true, message: '状态不能为空' },
          { type: 'number', message: '状态值格式不正确' }
        ]
      }
    }
  },
  watch: {
    'postForm.is_click_in_breadcrumb': {
      handler(val) {
        if (val === 0) {
          this.tempRedirect = this.postForm.redirect
          this.postForm.redirect = 'noRedirect'
        } else {
          this.postForm.redirect = this.tempRedirect !== '' ? this.tempRedirect : this.postForm.redirect
          this.tempRedirect = ''
        }
      },
      deep: true
    },
    'postForm.is_link': {
      handler(val) {
        if (val === 1) {
          this.rules.path = [
            { required: true, message: '路由地址不能为空' },
            { validator: validateHttpUrl, trigger: 'blur' }
          ]
        } else {
          this.rules.path = [
            { required: true, message: '路由地址不能为空' },
            { validator: validateRequire, trigger: 'blur' }
          ]
        }
      },
      deep: true
    }
  },
  methods: {
    submitForm() {
      if (!this.loading) {
        this.loading = true
        this.$refs.postForm.validate((valid, fields) => {
          // 判断规则是否通过验证
          if (valid) {
            const menu = Object.assign({}, this.postForm)
            // console.log(menu)
            if (!this.isEdit) {
              addAuthMenu(menu).then(response => {
                this.$notify({
                  title: '成功',
                  message: response.msg,
                  type: 'success',
                  duration: 2000
                })
                this.$emit('ended')
              }).catch(() => {
                this.loading = false
              })
            } else {
              menu.id = this.id
              editAuthMenu(menu).then(response => {
                this.$notify({
                  title: '成功',
                  message: response.msg,
                  type: 'success',
                  duration: 2000
                })
                this.$emit('ended')
              }).catch(() => {
                this.loading = false
              })
            }
          } else {
            this.loading = false
            for (const key in fields) {
              if (fields.hasOwnProperty(key)) {
                const element = fields[key]
                this.$message({
                  message: element[0].message,
                  type: 'error',
                  duration: 2000
                })
                return false
              }
            }
          }
        })
      }
    },
    getAuthMenuByID() {
      if (this.id !== 0) {
        getAuthMenuByID(this.id).then(response => {
          if (!response.data || response.data.length === 0) {
            this.isEdit = false
            this.changePid(this.pid)
            return
          }
          const {
            pid,
            name,
            title,
            icon,
            path,
            url,
            redirect,
            sort,
            hidden,
            is_link,
            is_click_in_breadcrumb,
            breadcrumb_show,
            always_show,
            no_cache,
            public_menu,
            status
          } = response.data
          this.postForm = {
            pid,
            name,
            title,
            icon,
            path,
            url,
            redirect,
            sort,
            hidden,
            is_link,
            breadcrumb_show,
            is_click_in_breadcrumb,
            always_show,
            no_cache,
            public_menu,
            status
          }
          this.isEdit = true
        }).catch(() => {
          this.isEdit = false
          this.toDefault()
        })
      } else {
        this.isEdit = false
        this.changePid(this.pid)
      }
    },
    toDefault() {
      this.$refs.postForm.resetFields()
      this.loading = false
    },
    getAllMenuNode() {
      getAllMenuNode().then(response => {
        const { data } = response
        this.menuOptions = data
        this.postForm.pid = this.pid
        this.getAuthMenuByID()
      })
    },
    changePid(value) {
      getChildrenCount(value).then(response => {
        const { count } = response
        this.postForm.sort = count + 1
      })
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
